﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Diagnostics;
using System.Data.Common;
using SplendidCRM._code;
using System.Text;

namespace SplendidCRM.Home
{
    public partial class Whereabouts : SplendidControl
    {
        private const string TABLE = "WhereaboutsTable";

        protected void Page_Load(object sender, EventArgs e)
        {
            ListHeader1.DivEditName = Edit.ClientID;
            if (!Page.IsPostBack)
            {
                GetTable(true);
                LoadData();
            }
        }

        private DataTable GetTable(DateTime beginDate, DateTime endDate)
        {
            DataTable dt = new DataTable();

            DbProviderFactory dbf = DbProviderFactories.GetFactory();
            using (IDbConnection con = dbf.CreateConnection())
            {
                StringBuilder sSQL = new StringBuilder();
                sSQL.AppendLine("SELECT ID, NAME, BEGINDATE, ENDDATE, DESCRIPTION, LOCATION ");
                sSQL.AppendLine("FROM WHEREABOUTS ");
                sSQL.AppendLine("WHERE (@begindate = BEGINDATE AND ENDDATE = BEGINDATE) OR ");
                sSQL.AppendLine("(BEGINDATE >= @begindate AND BEGINDATE < @enddate) OR ");
                sSQL.AppendLine("(ENDDATE >= @begindate AND ENDDATE < @enddate) OR");
                sSQL.AppendLine("( ");
                sSQL.AppendLine("    (@begindate BETWEEN BEGINDATE AND ENDDATE) AND ");
                sSQL.AppendLine("    @enddate BETWEEN BEGINDATE AND ENDDATE ");
                sSQL.AppendLine(") ");

                using (IDbCommand cmd = con.CreateCommand())
                {
                    cmd.CommandText = sSQL.ToString();
                    //Get just this months entries
                    Sql.AddParameter(cmd, "@begindate", beginDate);
                    Sql.AddParameter(cmd, "@enddate", endDate);

                    // 11/24/2006 Paul.  Use new Security.Filter() function to apply Team and ACL security rules.
                    //Security.Filter(cmd, m_sMODULE, "list");
                    //Sql.AppendParameter(cmd, Security.USER_ID, "ASSIGNED_USER_ID", false);
                    // 04/26/2008 Paul.  Move Last Sort to the database.

                    if (bDebug)
                        RegisterClientScriptBlock("WHEREABOUTS", Sql.ClientScriptBlock(cmd));

                    try
                    {
                        using (DbDataAdapter da = dbf.CreateDataAdapter())
                        {
                            ((IDbDataAdapter)da).SelectCommand = cmd;
                            da.Fill(dt);
                            //grdMain.DataSource = vwMain;
                            // 09/15/2005 Paul. We must always bind, otherwise a Dashboard refresh will display the grid with empty rows. 
                            // 04/26/2008 Paul.  Move Last Sort to the database.
                            //grdMain.DataBind();
                        }
                    }
                    catch (Exception ex)
                    {
                        SplendidError.SystemError(new StackTrace(true).GetFrame(0), ex);
                        lblError.Text = ex.Message;
                    }
                }
            }

            Session[TABLE] = dt;
            return dt;
        }

        private DataTable GetTable(bool reload)
        {
            if (Session[TABLE] == null || reload)
            {
                DateTime visibleDate = EventCalendar1.VisibleDate;
                if (visibleDate == DateTime.MinValue)
                    visibleDate = DateTime.Today;

                return GetTable(visibleDate.First().Date, visibleDate.Last().Date.AddDays(1));
            }

            return (DataTable)Session[TABLE];
        }

        private void LoadData()
        {
            EventCalendar1.EventSource = GetTable(false);
            EditGrid.DataSource = GetTable(false);
            EditGrid.DataBind();
        }

        protected void EditGrid_RowEditing(object sender, GridViewEditEventArgs e)
        {
            EditGrid.EditIndex = e.NewEditIndex;
            Edit.Style[HtmlTextWriterStyle.Display] = "inline";
            GetTable(true);
            LoadData();
        }

        protected void EditGrid_RowDeleted(object sender, GridViewDeletedEventArgs e)
        {

        }

        protected void EditGrid_RowUpdated(object sender, GridViewUpdatedEventArgs e)
        {
            
        }

        protected void EditGrid_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            EditGrid.EditIndex = -1;
            GetTable(true);
            LoadData();
        }

        protected void EditGrid_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            if (e.RowIndex != -1)
            {
                DbProviderFactory dbf = DbProviderFactories.GetFactory();
                using (IDbConnection con = dbf.CreateConnection())
                {
                    using (IDbCommand cmd = con.CreateCommand())
                    {
                        cmd.CommandType = CommandType.StoredProcedure;
                        cmd.CommandText = "spWHEREABOUTS_UPDATE";

                        GridView grd = (GridView)sender;

                        TextBox _begin = (TextBox)grd.Rows[e.RowIndex].FindControl("txt_Begin");
                        TextBox _end = (TextBox)grd.Rows[e.RowIndex].FindControl("txt_End");
                        TextBox _name = (TextBox)grd.Rows[e.RowIndex].FindControl("txt_Name");
                        TextBox _description = (TextBox)grd.Rows[e.RowIndex].FindControl("txt_Description");
                        TextBox _location = (TextBox)grd.Rows[e.RowIndex].FindControl("txt_Location");

                        //Get just this months entries
                        Sql.AddParameter(cmd, "@id", new Guid(((DataTable)Session[TABLE]).Rows[e.RowIndex]["Id"].ToString()));
                        Sql.AddParameter(cmd, "@begindate", Convert.ToDateTime(_begin.Text));
                        Sql.AddParameter(cmd, "@enddate", Convert.ToDateTime(_end.Text));
                        Sql.AddParameter(cmd, "@name", _name.Text);
                        Sql.AddParameter(cmd, "@description", _description.Text);
                        Sql.AddParameter(cmd, "@location", _location.Text);

                        if (bDebug)
                            RegisterClientScriptBlock("WHEREABOUTS", Sql.ClientScriptBlock(cmd));

                        try
                        {
                            bool closeCon = false;
                            if (con.State != ConnectionState.Open)
                            {
                                con.Open();
                                closeCon = true;
                            }
                            cmd.ExecuteNonQuery();
                            if (closeCon)
                                con.Close();
                        }
                        catch (Exception ex)
                        {
                            SplendidError.SystemError(new StackTrace(true).GetFrame(0), ex);
                            lblError.Text = ex.Message;
                        }
                    }
                }

                EditGrid.EditIndex = -1;
                Edit.Style[HtmlTextWriterStyle.Display] = "inline";

                GetTable(true);
                LoadData();
            }
        }

        protected void EditGrid_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            DbProviderFactory dbf = DbProviderFactories.GetFactory();
            using (IDbConnection con = dbf.CreateConnection())
            {
                using (IDbCommand cmd = con.CreateCommand())
                {
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.CommandText = "spWHEREABOUTS_Delete";


                    //Get just this months entries
                    Sql.AddParameter(cmd, "@id", new Guid(((DataTable)Session[TABLE]).Rows[e.RowIndex]["Id"].ToString()));

                    if (bDebug)
                        RegisterClientScriptBlock("WHEREABOUTS", Sql.ClientScriptBlock(cmd));

                    try
                    {
                        bool closeCon = false;
                        if (con.State != ConnectionState.Open)
                        {
                            con.Open();
                            closeCon = true;
                        }
                        cmd.ExecuteNonQuery();
                        if (closeCon)
                            con.Close();
                    }
                    catch (Exception ex)
                    {
                        SplendidError.SystemError(new StackTrace(true).GetFrame(0), ex);
                        lblError.Text = ex.Message;
                    }
                }
            }

            GetTable(true);
            LoadData();
        }

        protected void AddButton_Click(Object sender, EventArgs e)
        {
            DbProviderFactory dbf = DbProviderFactories.GetFactory();
            using (IDbConnection con = dbf.CreateConnection())
            {
                using (IDbCommand cmd = con.CreateCommand())
                {
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.CommandText = "spWHEREABOUTS_Update";

                    //Get just this months entries
                    Sql.AddParameter(cmd, "@id", Guid.Empty);
                    Sql.AddParameter(cmd, "@begindate", BeginDate.Value);
                    Sql.AddParameter(cmd, "@enddate", EndDate.Value);
                    Sql.AddParameter(cmd, "@name", Name.Text);
                    Sql.AddParameter(cmd, "@description", Description.Text);
                    Sql.AddParameter(cmd, "@location", Location.Text);

                    if (bDebug)
                        RegisterClientScriptBlock("WHEREABOUTS", Sql.ClientScriptBlock(cmd));

                    try
                    {
                        bool closeCon = false;
                        if (con.State != ConnectionState.Open)
                        {
                            con.Open();
                            closeCon = true;
                        }
                        cmd.ExecuteNonQuery();
                        if (closeCon)
                            con.Close();

                        //14/08/08 Jake. Clear textboxes now that values have been fetched and no errors
                        BeginDate.Value = DateTime.MinValue;
                        EndDate.Value = DateTime.MinValue;
                        Name.Text = string.Empty;
                        Description.Text = string.Empty;
                        Location.Text = string.Empty;
                    }
                    catch (Exception ex)
                    {
                        SplendidError.SystemError(new StackTrace(true).GetFrame(0), ex);
                        lblError.Text = ex.Message;
                    }
                }
            }

            GetTable(true);
            LoadData();
        }

        protected void EventCalendar1_VisibleMonthChanged(object sender, MonthChangedEventArgs e)
        {
            GetTable(true);
            LoadData();
        }

        protected void EventCalendar1_SelectionChanged(object sender, EventArgs e)
        {
            if (EventCalendar1.SelectedDate != DateTime.MinValue)
            {
                SelectionGrid.DataSource = GetTable(EventCalendar1.SelectedDate, EventCalendar1.SelectedDate.AddDays(1));
                SelectionGrid.DataBind();
                SelectedDay.Style[HtmlTextWriterStyle.Display] = "inline";
                SelectedDayHeader.Text = string.Format("Whereabouts on {0}", EventCalendar1.SelectedDate.ToLongDateString());
            }
            else
            {
                SelectedDay.Style[HtmlTextWriterStyle.Display] = "hidden";
            }
        }
    }
}